package com.hjm.common.utils.request;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.StringWriter;

/**
 * 
 *********************************************************.<br>
 * [类名] BasePF <br>
 * [描述] (这里用一句话描述这个类的作用) <br>
 * [作者] Nik_ <br>
 * [时间] 2018-12-26 下午5:48:45 <br>
 *********************************************************.<br>
 */
public class BasePF {
//    private static final Logger logger = Logger.getLogger(SignatureUtil.class);

    public static OutputFormat xmlOutputFormat() {
        // 设置XML文档格式
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        // 设置XML编码方式,即是用指定的编码方式保存XML文档到字符串(String),这里也可以指定为GBK或是ISO8859-1
        outputFormat.setEncoding("UTF-8");
        //outputFormat.setSuppressDeclaration(true); //是否生产xml头
        outputFormat.setIndent(true); //设置是否缩进
        outputFormat.setIndent("    "); //以四个空格方式实现缩进
        outputFormat.setNewlines(true); //设置是否换行
        outputFormat.setExpandEmptyElements(true);//双标签 true 单标签false
        return outputFormat;
    }
    
    public static String formatXml(String xml) throws DocumentException, IOException {
        Document doc = null; // 将字符串转为XML
        StringWriter stringWriter = null;
        XMLWriter xmlWriter = null;
        try {
            doc = DocumentHelper.parseText(xml);
            // stringWriter字符串是用来保存XML文档的
            stringWriter = new StringWriter();
            // xmlWriter是用来把XML文档写入字符串的(工具)
            xmlWriter = new XMLWriter(stringWriter, xmlOutputFormat());
            // 把创建好的XML文档写入字符串
            xmlWriter.write(doc);
            return stringWriter.toString();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } catch (DocumentException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                xmlWriter.close();
                stringWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
